import 'package:flutter/material.dart';
import 'package:flutter_refresh/flutter_refresh.dart';
import 'package:safety_platform/models/hidden_danger.dart';
import 'package:safety_platform/pages/services.dart';
import 'package:safety_platform/components/loading.dart';
import 'package:safety_platform/pages/hidden_danger/detail_page.dart';
import 'package:safety_platform/authentication.dart';
import 'package:safety_platform/models/login_user.dart';
import 'package:safety_platform/pages/hidden_danger/rectify_page.dart';
import 'package:safety_platform/pages/hidden_danger/exection_page.dart';
import 'package:safety_platform/pages/hidden_danger/verification_page.dart';

class _HistoryListWidget extends StatefulWidget {
  final String status;

  _HistoryListWidget(this.status);
  @override
  State<StatefulWidget> createState() => _HistoryListWidgetState();
}

class _HistoryListWidgetState extends State<_HistoryListWidget> {
  List<HiddenDanger> data;
  int count;
  int next;
  String status = 'init';
  Future<Null> onHeaderRefresh() async {
    data.clear();
    HiddenDangerPage page = await fetchHiddenDanger(status: widget.status);

    setState(() {
      data = page.results;
      count = page.count;
      next = page.next;
    });
  }

  Future<Null> onFooterRefresh() async {
    if (next == null) {
      print('沒有更多數據了');
      return;
    }
    HiddenDangerPage page =
        await fetchHiddenDanger(page: next, status: widget.status);
    setState(() {
      data.addAll(page.results);
      count = page.count;
      next = page.next;
    });
  }

  Widget columnText(String text) {
    return Padding(
      padding: EdgeInsets.fromLTRB(16, 2, 8, 2),
      child: Text(text,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(color: Colors.white)),
    );
  }

  void _onPageReturn(HiddenDanger hiddenDanger) {
    if (hiddenDanger != null) {
      this.data = data.where((d) {
        if (d.id != hiddenDanger.id) {
          return true;
        } else {
          if (d.status != hiddenDanger.status ||
              hiddenDanger.status != this.status) {
            return false;
          }
          return true;
        }
      }).toList();
      setState(() {});
    }
  }

  Widget itemBuilder(BuildContext context, int index) {
    print('index $index');
    HiddenDanger hd = data[index];
    return InkWell(
      onTap: () {
        LoginUser user = getCurrentUser();
        print(user.permissions);
        if (hd.status == 'created') {
          if (user.hasPerm('risk.approve_hiddendanger')) {
            Navigator.of(context)
                .push(MaterialPageRoute(
                    builder: (_) => HiddenDangerRectifyPage(
                          hiddenDanger: hd,
                        )))
                .then((hiddenDanger) => _onPageReturn(hiddenDanger));
          } else {
            Navigator.of(context)
                .push(MaterialPageRoute(
                    builder: (_) => HiddenDangerDetailPage(hd)))
                .then((hiddenDanger) {
              this.data = data.where((d) {
                if (d.id != hiddenDanger.id) {
                  return true;
                } else {
                  if (d.status != hiddenDanger.status ||
                      hiddenDanger.status != this.status) {
                    return false;
                  }
                  return true;
                }
              }).toList();
              setState(() {});
              print('返回 $hiddenDanger');
            });
          }
        } else if (hd.status == 'done') {
          Navigator.of(context)
              .push(
                  MaterialPageRoute(builder: (_) => VerificationPage(hiddenDanger:hd)))
              .then((hiddenDanger) => _onPageReturn(hiddenDanger));
        } else if (hd.status == 'approved') {
          Navigator.of(context)
              .push(MaterialPageRoute(
                  builder: (_) => HiddenDangerExectionPage(hiddenDanger: hd)))
              .then((hiddenDanger) => _onPageReturn(hiddenDanger));
        } else {
          Navigator.of(context).push(
              MaterialPageRoute(builder: (_) => HiddenDangerDetailPage(hd)));
        }
      },
      child: Card(
        margin: EdgeInsets.fromLTRB(8, 4, 4, 8),
        child: Container(
          // padding: EdgeInsets.all(8),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                child: Padding(
                  padding: EdgeInsets.fromLTRB(16, 8, 16, 8),
                  child: Text('隐患编号：${hd.id}'),
                ),
              ),
              Container(
                color: Theme.of(context).primaryColor,
                child: Row(
                  mainAxisSize: MainAxisSize.max,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    Expanded(
                        child: Container(
                      // color: Colors.red,
                      margin: EdgeInsets.symmetric(vertical: 8),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          columnText('更改人员'),
                          columnText('暂无数据'),
                          columnText('更新时间'),
                          columnText(
                              '${hd.updated.year}-${hd.updated.month}-${hd.updated.day}')
                        ],
                      ),
                      decoration: BoxDecoration(
                          border: Border(
                              right: BorderSide(
                        width: 0.5,
                        color: Colors.white,
                      ))),
                    )),
                    Expanded(
                      child: Container(
                        padding: EdgeInsets.symmetric(vertical: 8.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            columnText('检查部位'),
                            columnText('${hd.risk.name}'),
                            columnText('隐患级别'),
                            columnText(hiddenDangerGradeCodeToText(hd.grade)),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  @override
  void initState() {
    print("initState , $data");
    fetchHiddenDanger(status: widget.status).then((HiddenDangerPage page) {
      if (mounted) {
        if (page.count == 0) {
          setState(() {
            status = 'nodata';
          });
        } else {
          setState(() {
            status = 'loaded';
            count = page.count;
            next = page.next;
            data = page.results;
          });
        }
      }
    });
    data = List();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    switch (status) {
      case 'nodata':
        {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                // Icon(
                //   MyIconFont.jspjiancha,
                //   size: 60,
                //   color: Colors.grey,
                // ),
                Container(
                    child: Text('没有相关数据'), margin: EdgeInsets.only(top: 16.0)),
              ],
            ),
          );
        }
      case 'init':
        {
          return Center(
            child: Loading(),
          );
        }
    }
    return Refresh(
      onFooterRefresh: () => onFooterRefresh(),
      onHeaderRefresh: () => onHeaderRefresh(),
      child: ListView.builder(
        padding: EdgeInsets.only(top: 16),
        itemCount: data.length,
        itemBuilder: (context, index) => itemBuilder(context, index),
      ),
    );
  }
}

class HiddenDangerHistory extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _HiddenDangerHistoryState();
}

class _HiddenDangerHistoryState extends State<HiddenDangerHistory>
    with SingleTickerProviderStateMixin {
  TabController _controller;
  @override
  void initState() {
    super.initState();
    _controller = TabController(length: 5, vsync: this);
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  Widget _body() {
    return TabBarView(
      controller: _controller,
      children: <Widget>[
        _HistoryListWidget('created'),
        _HistoryListWidget('approved'),
        _HistoryListWidget('done'),
        _HistoryListWidget('verified'),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> children = ['已登记', '已安排', '已完成', '已验收'].map((s) {
      return Container(
        padding: EdgeInsets.all(8),
        child: Text(
          s,
          style: TextStyle(
            // fontSize: 16,
            fontWeight: FontWeight.w400,
          ),
        ),
      );
    }).toList();
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      appBar: AppBar(
        title: new Text("隐患历史"),
        elevation: 0,
        backgroundColor: Color.fromARGB(255, 27, 130, 210),
        centerTitle: true, //设置标题是否局中
        // bottomOpacity:0.5,
        bottom: TabBar(
          controller: _controller,
          tabs: children,
          indicatorColor: Colors.white,
        ),
      ),
      body: _body(),
    );
  }
}
